﻿using System;
using System.Linq;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using CuoDing.Core.BLL;
using CuoDing.Core.Model.Model;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using CuoDing.Core.Common;

//using Newtonsoft.Json;

namespace CuoDing.Core.Logs
{
    /// <summary>
    /// 操作日志处理
    /// </summary>
    public class LogHandler : ILogHandler
    {
        private readonly ILogger _logger;
        private readonly ISystemOperateLogBLL _systemOperateLogBLL;

        public LogHandler(ILogger<LogHandler> logger, ISystemOperateLogBLL systemOperateLogBLL)
        {
            _logger = logger;
            _systemOperateLogBLL = systemOperateLogBLL;
        }

        public async Task LogAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var sw = new Stopwatch();
            sw.Start();
            var actionExecutedContext = await next();
            sw.Stop();

            //操作参数
            var args = JsonConvert.SerializeObject(context.ActionArguments);
            //操作结果
            //var result1 = JsonConvert.SerializeObject(actionResult?.Value);

            try
            {
                var model = new SystemOperateLog
                {
                    Params = args,
                    ApiMethod = context.HttpContext.Request.Method.ToLower(),
                    ApiPath = context.ActionDescriptor.AttributeRouteInfo.Template.ToLower(),
                    ElapsedMilliseconds = sw.ElapsedMilliseconds.ObjToInt()
                };
                ObjectResult result = actionExecutedContext.Result as ObjectResult;
                if (result != null)
                {
                    model.Result = JsonConvert.SerializeObject(result.Value);
                    model.LogStatus = 1;
                }
                string ua = context.HttpContext.Request.Headers["User-Agent"];
                var client = UAParser.Parser.GetDefault().Parse(ua);
                var device = client.Device.Family;
                device = device.ToLower() == "other" ? "" : device;
                model.Browser = client.UA.Family;
                model.Os = client.OS.Family;
                model.Device = device;
                model.BrowserInfo = ua;
                model.IP = IPHelper.GetIP(context?.HttpContext?.Request);
                await _systemOperateLogBLL.AddLog(model);
            }
            catch (Exception ex)
            {
                _logger.LogError("操作日志插入异常：{@ex}", ex);
            }
        }
    }
}
